package cn.mumzone.pos.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosAlertDialog;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.model.InventoryDetailEntity;
import cn.mumzone.pos.model.InventoryGoodsEntity;
import cn.mumzone.pos.presenter.InventoryDetailPresenter;
import cn.mumzone.pos.presenter.contract.InventoryDetailContract;
import cn.mumzone.pos.ui.adapter.ADA_InventoryGoods;
import cn.mumzone.pos.ui.adapter.ADA_RepoGoods;
import cn.mumzone.pos.ui.widgets.refresh.SmartRefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener;

/**
 * 盘点单详情
 * <p>
 * Created by qiuzhenhuan on 2019/10/11.
 */

public class ACT_InventoryDetail extends BaseActivity<InventoryDetailPresenter> implements InventoryDetailContract.View {

    private static final String KEY_ORDER_ID = "order_id";
    private static final int REQUEST_CODE = 3001;

    @BindView(R.id.et_scan)
    EditText etScan;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_order_code)
    TextView tvOrderCode;
    @BindView(R.id.tv_repository)
    TextView tvRepository;
    @BindView(R.id.tv_check_type)
    TextView tvCheckType;
    @BindView(R.id.tv_check_time)
    TextView tvCheckTime;
    @BindView(R.id.ll_remark)
    LinearLayout llRemark;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.et_remark)
    TextView etRemark;

    @BindView(R.id.tv_search_goods)
    TextView tvSearchGoods;
    @BindView(R.id.rv_check_goods)
    RecyclerView rvCheckGoods;

    @BindView(R.id.view_bottom)
    View viewBottom;
    @BindView(R.id.rl_bottom)
    RelativeLayout rlBottom;
    @BindView(R.id.btn_confirm)
    LoadingButton btmConfirm;

    private String orderId;

    //:0:未开始 1:进行中 2:未审核 3:审核完成 4:已驳回'
    private String inventoryStatus;

    private ADA_InventoryGoods inventoryGoodsAdapter;

    private AlertDialog searchDialog;
    private SmartRefreshLayout refreshLayout;
    private ImageView ivClearInput;
    private RadioButton rbSearch;
    private EditText etSearch;
    private RecyclerView rvSearchList;
    private TextView tvSearchConfirm;
    private ADA_InventoryGoods searchAdapter;

    private AlertDialog mScanGoodsDialog;
    private TextView tvScanConfirm;
    private ADA_InventoryGoods mScanGoodsAdapter;

    private PosAlertDialog confirmStartDialog;
    private PosAlertDialog backAlertDialog;

    private boolean isScanExecuted = false;


    @Override
    protected void initEventAndData() {

        initSearchDialog();

        initScanGoodsDialog();

        etScan.setInputType(InputType.TYPE_NULL);
        etScan.requestFocus();
        EditTextUtil.hideSoftInputMethod(mContext, etScan);
        etScan.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (!InventoryDetailEntity.INVENTORY_STATUS_PROGRESSING.equals(inventoryStatus)) {
                    return false;
                }
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.loadInventoryGoods(orderId, code, false);
                    }
                    etScan.setText("");
                    isScanExecuted = true;
                }
                return true;
            }
        });


        rvCheckGoods.setLayoutManager(new LinearLayoutManager(mContext));
        inventoryGoodsAdapter = new ADA_InventoryGoods(mContext);
        rvCheckGoods.setAdapter(inventoryGoodsAdapter);
        mPresenter.loadInventoryDetails(orderId);
        mPresenter.loadInventoryGoods(orderId, "", false);
    }

    private void initSearchDialog() {
        searchDialog = new PosDialog.PosBuilder(mContext, PosDialog.DIALOG_BLACK_TITLE)
                .setRealDialogContent(R.layout.dialog_search_inventory)
                .setUseRadiusBg(false)
                .setDialogTitle("搜索商品")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        searchDialog.setCanceledOnTouchOutside(true);
        searchDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN |
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        etSearch = searchDialog.getView(R.id.et_search_goods);
        refreshLayout = searchDialog.getView(R.id.refresh_layout);
        ivClearInput = searchDialog.getView(R.id.iv_clear_input);
        rbSearch = searchDialog.getView(R.id.rb_search);
        rvSearchList = searchDialog.getView(R.id.rv_cart_goods);
        tvSearchConfirm = searchDialog.getView(R.id.tv_confirm);
        tvSearchConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateLocalGoodsCount(searchAdapter.getDataList());
                closeDialog(searchDialog);
            }
        });


        rvSearchList.setLayoutManager(new LinearLayoutManager(mContext));
        searchAdapter = new ADA_InventoryGoods(mContext);

        searchAdapter.setOnGoodsCountChangeListener(new ADA_InventoryGoods.OnGoodsCountChangeListener() {
            @Override
            public void onGoodsCountChanged(String goodsId, String batchId, int count) {
//                updateLocalGoodsCount(goodsId, batchId, count);
            }
        });
        searchAdapter.setInventoryStatus(InventoryDetailEntity.INVENTORY_STATUS_PROGRESSING);
        rvSearchList.setAdapter(searchAdapter);
        etSearch.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                boolean isInputNotEmpty = !TextUtils.isEmpty(etSearch.getText().toString());
                ivClearInput.setVisibility(isInputNotEmpty ? View.VISIBLE : View.GONE);
                rbSearch.setEnabled(isInputNotEmpty);
                rbSearch.setChecked(isInputNotEmpty);
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    EditTextUtil.hideSoftInput(mContext, etSearch);
                    refreshLayout.autoRefresh();
                }
                return false;
            }
        });
        ivClearInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(etSearch.getText().toString())) {
                    etSearch.setText("");
                    searchAdapter.clear();
                    searchDialog.toggleShowEmpty(true, R.id.ll_goods, R.drawable.svg_ic_empty_coupon, "暂无商品");
                }
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                String keyword = etSearch.getText().toString().trim();
                mPresenter.loadInventoryGoods(orderId, keyword, true);
            }
        });
        rbSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditTextUtil.hideSoftInput(mContext, etSearch);
                refreshLayout.autoRefresh();
            }
        });
        searchDialog.toggleShowEmpty(true, R.id.ll_goods, R.drawable.svg_ic_empty_coupon, "暂无商品");
    }

    private void initScanGoodsDialog() {
        mScanGoodsDialog = new PosDialog.PosBuilder(mContext, PosDialog.DIALOG_BLACK_TITLE)
                .setRealDialogContent(R.layout.dialog_scan_inventory_goods)
                .setUseRadiusBg(false)
                .setDialogTitle("扫码查询商品")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        mScanGoodsDialog.setCanceledOnTouchOutside(true);
        final EditText etCode = mScanGoodsDialog.getView(R.id.et_code);
        etCode.setInputType(InputType.TYPE_NULL);
        etCode.requestFocus();
        EditTextUtil.hideSoftInputMethod(mContext, etCode);
        etCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.loadInventoryGoods(orderId, code, false);
                    }
                    isScanExecuted = true;
                    v.setText("");
                }
                return true;
            }
        });

        tvScanConfirm = mScanGoodsDialog.getView(R.id.tv_confirm);
        tvScanConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateLocalGoodsCount(searchAdapter.getDataList());
                closeDialog(searchDialog);
            }
        });
        RecyclerView rvGoodsList = mScanGoodsDialog.getView(R.id.rv_goods_list);
        rvGoodsList.setLayoutManager(new LinearLayoutManager(mContext));
        mScanGoodsAdapter = new ADA_InventoryGoods(mContext);
        mScanGoodsAdapter.setInventoryStatus(InventoryDetailEntity.INVENTORY_STATUS_PROGRESSING);
        rvGoodsList.setAdapter(mScanGoodsAdapter);
        mScanGoodsDialog.setOnClickListener(R.id.tv_confirm, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateLocalGoodsCount(mScanGoodsAdapter.getDataList());
                closeDialog(mScanGoodsDialog);
            }
        });
        mScanGoodsAdapter.setOnGoodsCountChangeListener(new ADA_InventoryGoods.OnGoodsCountChangeListener() {
            @Override
            public void onGoodsCountChanged(String goodsId, String batchId, int count) {
//                updateLocalGoodsCount(goodsId, batchId, count);
            }
        });
        mScanGoodsDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                etCode.clearFocus();
                etScan.requestFocus();
            }
        });
    }

    private void updateLocalGoodsCount(List<InventoryGoodsEntity> goodsEntities) {
        for (InventoryGoodsEntity goodsEntity : goodsEntities) {
            for (InventoryGoodsEntity localGoods : inventoryGoodsAdapter.getDataList()) {
                String newGoodsBatch = JSON.toJSONString(goodsEntity.getGoodsBatchNumList());
                String oldGoodsBatch = JSON.toJSONString(localGoods.getGoodsBatchNumList());
                if (localGoods.getGoodsId().equals(goodsEntity.getGoodsId()) && !
                        newGoodsBatch.equals(oldGoodsBatch)) {
                    localGoods.setGoodsBatchNumList(JSON.parseArray(newGoodsBatch, InventoryGoodsEntity.GoodsBatchNumListBean.class));
                    break;
                }
            }
        }
        inventoryGoodsAdapter.notifyDataSetChanged();
    }

    private void syncLocalGoodsCount(List<InventoryGoodsEntity> newList) {
        for (InventoryGoodsEntity newGoodsEntity : newList) {
            for (InventoryGoodsEntity goodsEntity : inventoryGoodsAdapter.getDataList()) {
                String newGoodsBatch = JSON.toJSONString(newGoodsEntity.getGoodsBatchNumList());
                String oldGoodsBatch = JSON.toJSONString(goodsEntity.getGoodsBatchNumList());
                if (newGoodsEntity.getGoodsId().equals(goodsEntity.getGoodsId()) && !
                        newGoodsBatch.equals(oldGoodsBatch)) {
                    newGoodsEntity.setGoodsBatchNumList(JSON.parseArray(oldGoodsBatch, InventoryGoodsEntity.GoodsBatchNumListBean.class));
                }
            }
        }
    }

    @Override
    public void showInventoryDetails(InventoryDetailEntity detailEntity) {
        inventoryStatus = detailEntity.getInventoryStatus();
        tvRepository.setText(StringUtils.get(detailEntity.getWarehouseName()));
        tvName.setText(StringUtils.get(detailEntity.getUserName()));
        tvOrderCode.setText(StringUtils.get(detailEntity.getInventoryCode()));
        tvStatus.setText(formatStatus(detailEntity.getInventoryStatus()));
        tvCheckType.setText(formatCheckType(detailEntity.getInventoryType()));
        tvCheckTime.setText(AppDateUtil.getTimeStamp(Long.valueOf(detailEntity.getCreateTime()),
                AppDateUtil.YYYY_MM_DD_HH_MM2));
        tvRemark.setText(StringUtils.get(detailEntity.getInventoryRemark()));

        updateWithStatus();
    }

    @Override
    public void showInventoryGoods(List<InventoryGoodsEntity> goodsList) {
        inventoryGoodsAdapter.update(goodsList, true);
    }

    @Override
    public void showSearchGoods(List<InventoryGoodsEntity> goodsList) {
        refreshLayout.finishRefresh();
        if (!ListUtil.isListEmpty(goodsList)) {
            tvSearchConfirm.setEnabled(true);
            searchDialog.toggleShowEmpty(false, R.id.ll_goods);
            syncLocalGoodsCount(goodsList);
            searchAdapter.update(goodsList, true);
        } else {
            tvSearchConfirm.setEnabled(false);
            searchDialog.toggleShowEmpty(true, R.id.ll_goods, R.drawable.svg_ic_empty_coupon, "未搜索到商品");
        }
    }

    @Override
    public void showScanGoods(List<InventoryGoodsEntity> goodsList) {
        isScanExecuted = false;
        showDialog(mScanGoodsDialog);
        mScanGoodsDialog.getView(R.id.et_code).requestFocus();
        if (!ListUtil.isListEmpty(goodsList)) {
            tvScanConfirm.setEnabled(true);
            mScanGoodsDialog.toggleShowEmpty(false, R.id.ll_goods);
            syncLocalGoodsCount(goodsList);
            mScanGoodsAdapter.update(goodsList, true);
        } else {
            tvScanConfirm.setEnabled(false);
            mScanGoodsDialog.toggleShowEmpty(true, R.id.ll_goods, R.drawable.svg_ic_empty_coupon, "未搜索到商品");
        }
    }

    @Override
    public void showError(String msg) {
        if (confirmStartDialog != null) {
            confirmStartDialog.cancelLoading();
        }
        isScanExecuted = false;
        refreshLayout.finishRefresh();
        tvSearchConfirm.setEnabled(false);
        super.showError(msg);
    }

    @Override
    public void showInventoryProgress() {
        if (confirmStartDialog != null) {
            confirmStartDialog.cancelLoading();
        }
        if ("0".equals(inventoryStatus)) {
            inventoryStatus = "1";
            updateWithStatus();
            btmConfirm.stopLoading("提交盘点结果");
        } else if ("1".equals(inventoryStatus)) {
            inventoryStatus = "3";
            updateWithStatus();
        }

    }

    @OnClick({R.id.btn_confirm, R.id.tv_search_goods, R.id.iv_back, R.id.et_remark})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                showBackDialog();
                break;
            case R.id.btn_confirm:
                if ("0".equals(inventoryStatus)) {
                    confirmStartDialog = new PosAlertDialog.Builder(mContext)
                            .setRemindText("提交盘点结果之前盘点商品将一直不能售卖、不能出入库，确定要开始盘点吗？")
                            .setPrimaryText("开始盘点")
                            .setPrimaryLoadingText("开始盘点")
                            .setUseLoadingButton(true)
                            .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                                @Override
                                public void onConfirmClick(View view, Dialog dialog) {
                                    mPresenter.doUpdateInventoryStatus(orderId, "1");
                                }
                            }).build();
                    confirmStartDialog.show();
                } else if ("1".equals(inventoryStatus)) {
                    String remark = etRemark.getText().toString().trim();
                    ACT_InventoryResult.startAcForResult(mContext, orderId, inventoryGoodsAdapter.getDataList(), remark, REQUEST_CODE);
                } else {
                    showError("审核中，无法盘点");
                }
                break;
            case R.id.tv_search_goods:
                showDialog(searchDialog);
                tvSearchConfirm.setEnabled(false);
                etSearch.setText("");
                searchAdapter.clear();
                searchDialog.toggleShowEmpty(true, R.id.ll_goods, R.drawable.svg_ic_empty_coupon, "暂无商品");
                break;
            case R.id.et_remark:
                showRemarkDialog();
                break;
        }
    }


    private void updateWithStatus() {

        if ("3".equals(inventoryStatus)) {
            llRemark.setVisibility(View.VISIBLE);
            viewBottom.setVisibility(View.GONE);
            rlBottom.setVisibility(View.GONE);
            etRemark.setVisibility(View.GONE);
            tvSearchGoods.setVisibility(View.GONE);

        } else if ("1".equals(inventoryStatus)) {
            etRemark.setVisibility(View.VISIBLE);
            tvSearchGoods.setVisibility(View.VISIBLE);
            viewBottom.setVisibility(View.VISIBLE);
            rlBottom.setVisibility(View.VISIBLE);
            btmConfirm.setText("提交盘点结果");
        } else {
            etRemark.setVisibility(View.GONE);
            llRemark.setVisibility(View.GONE);
            tvSearchGoods.setVisibility(View.GONE);

            viewBottom.setVisibility(View.VISIBLE);
            rlBottom.setVisibility(View.VISIBLE);
            btmConfirm.setText("开始盘点");

        }
        // TODO: 2019/10/18 暂时隐藏备注
//        llRemark.setVisibility(View.GONE);
//        etRemark.setVisibility(View.GONE);
        etScan.requestFocus();

        inventoryGoodsAdapter.setInventoryStatus(inventoryStatus);
        inventoryGoodsAdapter.notifyDataSetChanged();
    }

    private String formatCheckType(String inventoryType) {
        switch (inventoryType) {
            case "0":
                return "日盘";
            case "1":
                return "周盘";
            default:
                return "月盘";
        }
    }

    private String formatStatus(String inventoryStatus) {
        switch (inventoryStatus) {
            case "0":
                return "未开始的盘点单";
            case "3":
                return "已完成的盘点单";
            default:
                return "进行中的盘点单";
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            mPresenter.loadInventoryDetails(orderId);
            mPresenter.loadInventoryGoods(orderId, "", false);
        }
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        orderId = extras.getString(KEY_ORDER_ID);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showBackDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showBackDialog() {
        if (InventoryDetailEntity.INVENTORY_STATUS_PROGRESSING.equals(inventoryStatus)) {

            backAlertDialog = new PosAlertDialog.Builder(mContext)
                    .setRemindText("返回后盘点商品依然无法出入库、无法售卖，且已经盘点的结果不会保存，确定要中断盘点吗？")
                    .setPrimaryText("继续盘点")
                    .setSecondaryText("中断盘点")
                    .setUseLoadingButton(false)
                    .setOnCancelClickListener(new PosAlertDialog.OnCancelClickListener() {
                        @Override
                        public void onCancelClick(View view, Dialog dialog) {
                            backAlertDialog.dismiss();
                            finish();
                        }
                    })
                    .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                        @Override
                        public void onConfirmClick(View view, Dialog dialog) {
                            backAlertDialog.dismiss();
                        }
                    }).build();
            backAlertDialog.show();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDialog(searchDialog, confirmStartDialog, backAlertDialog);
    }

    @Override
    protected int getLayout() {
        return R.layout.act_check_stock_goods;
    }


    public static void startAc(Context context, String orderId) {
        Intent intent = new Intent(context, ACT_InventoryDetail.class);
        intent.putExtra(KEY_ORDER_ID, orderId);
        context.startActivity(intent);
    }

    private void showRemarkDialog() {
        final AlertDialog remarkDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_stock_remark)
                .setDialogTitle("备注")
                .setWidthAndHeight(438, -2)
                .show();

        final TextView tvLimit = remarkDialog.getView(R.id.tv_limit);
        final EditText view = remarkDialog.getView(R.id.et_stock_remark);
        view.setText(etRemark.getText().toString());
        view.requestFocus();
        view.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                tvLimit.setText(view.getText().toString().length() + "/200");
            }
        });

        View lbConfirm = remarkDialog.getView(R.id.lb_confirm);
        lbConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etRemark.setText(view.getText().toString());
                remarkDialog.dismiss();
            }
        });
    }

}
